﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iOak.Business.Users;
using iOak.Domain.Users;
using System.Web.Security;
using iOak.Common;
using iOak.Business.Authentication;
using System.Configuration;

namespace iOak.Web
{
    public partial class SignIn : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnSignIn_Click(object sender, EventArgs e)
        {
            var username = txtUsername.Text.Trim();
            var password = txtPassword.Text.Trim();

            var userService = new UserService();
            var authenticationService = new FormsAuthenticationService();
            if (userService.ValidateUser(username, password))
            {
               // FormsAuthentication.SetAuthCookie(username, false);   

                var user = userService.GetUserByName(username);

                // sign in user
                authenticationService.SignIn(user, false);

                Guid wndId = Guid.Parse(ConfigurationManager.AppSettings["wndId"]);
                if (user.CompanyId.Equals(wndId))
                {
                    Response.Redirect("~/Administration/Default.aspx");
                }
                else
                {
                    String redirectUrl = FormsAuthentication.GetRedirectUrl(username, true);
                    if (string.IsNullOrEmpty(redirectUrl))
                    {
                         Response.Redirect(redirectUrl);
                    }
                    else
                    {
                        Response.Redirect("~/Default.aspx");
                    }
                }
            }
            else
            {
                ClientScript.RegisterStartupScript(Page.GetType(), "showWarnning", "alert('您提供的登录凭据是错误的,请重新登录！')", true);
            }
        }

        protected void btnRegist_Click(object sender, EventArgs e) 
        {
            this.Response.Redirect("CompanyRegister.aspx");
        }
    }
}